<template>
  <div class="fba-print-wrap">
    <div class="print-setting">
      <ChoosePrintList :selectWidth="210" ref="choosePrintRef" style="margin-bottom: 10px" @getLodop="getLodop">
        <template #ipUrl>
          <p class="label">选择云主机：</p>
        </template>
        <template #bridgelabel>
          <p class="label">选择端桥：</p>
        </template>
        <template #printerlabel>
          <p class="label">选择打印机：</p>
        </template>
      </ChoosePrintList>
      <div class="set-item flex-c">
        <p class="label">打印份数：</p>
        <a-input-number size="small" v-model="printNum" :min="1" />
        <span class="unit">份</span>
      </div>
      <div class="set-item" style="margin-top: 30px">
        <p style="font-weight: bold; margin-bottom: 10px">选择打印模板：</p>
        <a-dropdown position="bl" trigger="hover">
          <a-button class="gray-outline flex-c-sb" style="min-width: 160px"> {{ currentTemp.templateName || '默认模板' }} <icon-down /> </a-button>
          <template #content>
            <a-doption @click="resetTemp">默认模板</a-doption>
            <a-doption v-for="(item, i) in tempList" :key="i" @click="changeTemplate(item)">{{ item.templateName }}</a-doption>
          </template>
        </a-dropdown>
      </div>
      <!-- <div class="set-item" style="margin-top: 10px">
        <p style="font-weight: bold; margin-bottom: 10px">图片尺寸：</p>
        <ul class="img-size-list">
          <li v-for="size in imgSizeList" :key="size" @click="editForm.imgSize = size" :style="{ width: size + 'px', height: size + 'px' }" :class="{ active: editForm.imgSize == size }">{{ size }}</li>
        </ul>
      </div> -->
      <div class="set-item" style="margin-top: 20px">
        <p>
          <span style="font-weight: bold">可选字段：</span>
        </p>
        <a-checkbox-group v-model="editForm.fieldList" @change="selItem">
          <p style="margin: 10px 0 5px">单据字段：</p>
          <a-checkbox style="width: 115px; margin-right: 5px" v-for="(key, val) in billFieldList" :key="val" :value="val">{{ key }}</a-checkbox>
        </a-checkbox-group>
        <a-checkbox-group v-model="editForm.propsFieldList" @change="selItem">
          <p style="margin: 10px 0 5px">定制信息：</p>
          <a-checkbox style="width: 115px; margin-right: 5px" v-for="(val, key) in propFieldMap" :key="key" :value="val.code">{{ val.name }}</a-checkbox>
        </a-checkbox-group>
      </div>

      <div>
        <p>
          <span style="font-weight: bold">打印单据：</span>
        </p>

        <a-table size="small" :bordered="{ cell: true }" :pagination="false" :data="tableList" :scroll="{ y: '100px' }">
          <template #columns>
            <a-table-column title="序号" #cell="{ rowIndex }" :width="60">{{ rowIndex + 1 }}</a-table-column>
            <a-table-column title="单据号" #cell="{ record }">{{ record.customCode }}</a-table-column>
          </template>
        </a-table>
      </div>

      <div class="handle-btn-w">
        <a-space>
          <a-button class="gray-outline" size="medium" @click="closePage">取消打印</a-button>
          <AddPrintTemp :currentTemp="currentTemp" templateCode="ZDP_PRINT_CUSTOM_ORDER" :content="editForm" @success="getTemplateList" />
          <a-button type="primary" size="medium" @click="toPrintPre" :loading="submitLoading">确认打印</a-button>
        </a-space>
      </div>
    </div>
    <div class="fba-list-w" ref="printDomContainer">
      <div class="item mb10" v-for="(item, index) of tableList" :key="index">
        <div class="top" style="overflow: hidden; line-height: 40px; font-size: 10px">
          <div style="font-size: 16px; font-weight: bold; float: left">定制编号</div>
          <div style="float: left; margin-left: 10px">
            <img style="height: 50px" :src="createCode(item.customCode, 60)" />
          </div>
          <div style="float: left; margin-left: 10px">{{ item.customCode }}</div>
          <div style="margin-left: 10px; float: left">
            <span>打印人：</span>
            <span>{{ userStore.userName }}</span>
          </div>
          <div style="float: left; margin-left: 10px">
            <span>打印时间：</span>
            <span>{{ $setTime(new Date()) }}</span>
          </div>
        </div>
        <div style="margin-top: 20px; overflow: hidden">
          <div style="width: 200px; float: left">
            <img style="width: 80px; height: 80px; margin-right: 5px; margin-bottom: 5px" v-for="(img, imgIndex) of getImgList(item)" :key="imgIndex" :src="img.url" alt="" />
          </div>
          <div>
            <div style="float: left">
              <div style="overflow: hidden; height: 30px; line-height: 30px">
                <img style="height: 30px; float: left" :src="createCode($extract(item, 'product.productSku'), 30)" alt="" />
                <div style="float: left; margin-left: 10px">SKU：{{ $extract(item, 'product.productSku') }}</div>
              </div>
              <div style="margin-top: 10px; width: 524px; overflow: hidden">
                <div style="border: 1px solid #e5e6eb; width: 260px; float: left; overflow: hidden" v-for="(fieldItem, index) of defaultField" :key="index">
                  <span style="font-size: 10px; float: left; padding-left: 10px; background-color: #f7f8fa; min-height: 21px; line-height: 21px; width: 80px; border-right: 1px solid #e5e6eb">{{ fieldItem.name }}</span>
                  <span style="width: 160px; min-height: 19px; float: left; padding: 2px 3px; font-size: 10px"> {{ nameGetValue(item, fieldItem) }} </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import brcode from '@/assets/brcode.png'
  import brcode2 from '@/assets/brcode2.png'
  import { useRouter, useRoute } from 'vue-router'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import useUserStore from '@/store/modules/user'
  import dayjs from 'dayjs'
  import { parseJson } from '@/utils'
  import ChoosePrintList from '@/components/Print/choosePrintList.vue'
  import { findTemplateList } from '@/api/export'
  import { pageCustomOrderPurchase, supplierPageCustomOrderPurchase } from '@/api/purchase'
  import JsBarcode from 'jsbarcode'
  const printDomContainer = ref()
  const billFieldList = {
    customCode: '定制编号',
    productSKU: '产品SKU',
    qtyPurchase: '数量',
    companyName: '销售公司',
    salerName: '销售员',
    purchaseCompanyName: '采购公司',
    purchaserName: '采购员',
    gmtSubmitPurchase: '提交时间',
    gmtExpectDelivery: '期望交期',
    supplierCompanyName: '供应商',
    semiSupplier: '毛坯供应方',
    semiWarehouseName: '毛坯领用仓',
  }
  const propFieldMap = ref<any>([
    { code: 'customType', name: '定制类型' },
    { code: 'material', name: '材质' },
    { code: 'fontTxt', name: '刻字内容' },
    { code: 'fontFamily', name: '字体' },
    { code: 'platinColor', name: '电镀颜色' },
    { code: 'ringSize', name: '戒指尺码' },
    { code: 'stone', name: '石头' },
    { code: 'chainList', name: '链条' },
    { code: 'fontPrint', name: '字印' },
    { code: 'remark', name: '备注' },
  ])
  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const router = useRouter()
  const submitLoading = ref(false)
  const userStore = useUserStore()
  const printNum = ref(1)
  const editForm = ref<any>({
    imgSize: 60,
    fieldList: [],
    propsFieldList: [],
  })

  const choosePrintRef = ref()
  const currentTemp = ref<any>({})
  const tempList = ref<Array<any>>([])
  const tableList = ref<Array<any>>([])
  const defaultField = ref<Array<any>>([])
  let LODOP: any = {}

  //获取导出模板
  async function getTemplateList() {
    const res: any = await findTemplateList({ templateType: 2, templateCode: 'ZDP_PRINT_CUSTOM_ORDER' })
    tempList.value = res?.data || []
  }
  //切换模板
  function changeTemplate(item: any) {
    defaultField.value = []
    currentTemp.value = item
    editForm.value = parseJson(item.templateContent, [])
    selItem()
  }
  function resetTemp() {
    editForm.value['fieldList'] = []
    editForm.value['propsFieldList'] = []
    editForm.value['propsFieldList'] = propFieldMap.value.map((e: any) => e.code)
    for (const key in billFieldList) {
      editForm.value['fieldList'].push(key)
    }
    selItem()
  }

  function selItem() {
    defaultField.value = getFilxedList()
  }

  // 获取所有自定义显示字段
  function getFilxedList() {
    let list: Array<any> = []
    editForm.value.fieldList?.forEach((key: string) => {
      list.push({ name: billFieldList[key], key: key, type: 1 })
    })
    editForm.value.propsFieldList?.forEach((key: string) => {
      list.push({ name: propFieldMap.value.find((e: any) => e.code == key).name, key: key, type: 2 })
    })
    return list
  }

  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.go(-1)
  }
  function getLodop(val: any) {
    LODOP = val
  }

  function addPrint() {
    // 纸张初始化
    LODOP.PRINT_INIT('打印定制单')
    // 横向打印
    // LODOP.SET_PRINT_PAGESIZE(2)

    //  指定打印机设备
    let { type, bridgeIDandName, printerIndex } = choosePrintRef.value.getBridgeInfo()
    if (type === 1) {
      LODOP.SET_BRIDGE_INDEX(bridgeIDandName + ',' + printerIndex)
    } else {
      LODOP.SET_PRINTER_INDEX(printerIndex)
    }

    LODOP.SET_SHOW_MODE('LANDSCAPE_DEFROTATED', 1)
    let arr = printDomContainer.value.children
    arr.forEach((item: any, index: number) => {
      if (index > 0 && arr.length > 1 && index % 2 == 0) {
        LODOP.NewPageA()
      }
      if ((index + 1) % 2 != 0) {
        LODOP.ADD_PRINT_HTM(20, 20, 1000, 500, item.innerHTML)
      } else {
        LODOP.ADD_PRINT_HTM(600, 20, 1000, 500, item.innerHTML)
      }
    })
  }
  // 打印预览
  function toPrintPre() {
    addPrint()
    LODOP.PREVIEW()
  }

  const getImgList = (info: any) => {
    return info?.customInfo?.customPicList || []
  }

  const getList = async () => {
    let arr = sessionStorage.getItem('customOrderIds').split(',')
    let params = {
      idList: arr,
    }

    let from = route.query.from
    if (from != 'supplier') {
      const res: any = await pageCustomOrderPurchase(params)
      tableList.value = res?.data?.records || []
    } else {
      const res: any = await supplierPageCustomOrderPurchase(params)
      tableList.value = res?.data?.records || []
    }
  }

  const init = async () => {
    await getTemplateList()
    if (tempList.value.length) {
      changeTemplate(tempList.value[0])
    }
    getList()

    // editForm.value['propsFieldList'] = propFieldMap.value.map((e: any) => e.code)
    // for (const key in billFieldList) {
    //   editForm.value['fieldList'].push(key)
    // }
  }

  const getfittingName = (data: any) => {
    let arr = data?.customInfo?.chainList || []
    let str = arr.map((e: any) => e.fittingName).join(',')
    return `${str.slice(0, 16)}...`
  }

  function nameGetValue(data: any, fieldData: any) {
    if (fieldData.type == '2') {
      return fieldData.key != 'chainList' ? data?.customInfo[fieldData.key] : getfittingName(data)
    } else {
      let str = ''
      switch (fieldData.key) {
        case 'customCode':
        case 'qtyPurchase':
        case 'companyName':
          str = data[fieldData.key]
          break
        case 'productSKU':
          str = data?.product?.productSku
          break
        case 'salerName':
          str = data?.saler?.name
          break
        case 'purchaseCompanyName':
          str = data?.purchaseCompany?.companyName
          break
        case 'purchaserName':
          str = data?.purchaser?.name
          break
        case 'gmtSubmitPurchase':
          str = dayjs(data.gmtSubmitPurchase).format('YYYY-MM-DD HH:mm:ss')
          break
        case 'gmtExpectDelivery':
          str = dayjs(data.gmtExpectDelivery).format('YYYY-MM-DD')
          break

        case 'supplierCompanyName':
          str = data?.supplierCompany?.companyName
          break
        case 'semiSupplier':
          str = getSupplierName(data)
          break
        case 'semiWarehouseName':
          str = data?.supplierCloseCost?.semiWarehouseName
          break
      }
      return str
    }
  }

  const getSupplierName = (data: any) => {
    if (data.supplierCloseCost.semiNoPick) {
      return '供应商'
    } else {
      return data.supplierCloseCost.semiWarehouseCode == 'CK86' ? '需求方' : '采购方'
    }
  }

  const createCode = (code: string, height: number) => {
    const canvas = document.createElement('canvas')
    JsBarcode(canvas, code, {
      format: 'CODE128',
      width: 2,
      height: height,
      displayValue: false,
    })

    return canvas.toDataURL('image/png')
  }

  onMounted(init)
</script>
<style lang="less" scoped>
  .fba-print-wrap {
    display: flex;
    height: calc(100vh - @menuHeight);
    .print-setting {
      background-color: #fff;
      margin-right: 5px;
      height: 100%;
      flex-shrink: 0;
      width: 400px;
      padding: 20px;
      .title {
        font-size: 16px;
        margin-bottom: 20px;
        font-weight: bold;
      }
      :deep(.printer-w .label) {
        width: 100px;
        flex-shrink: 0;
        text-align: right;
        color: var(--color-text-1);
      }
      .set-item {
        margin-bottom: 15px;
        .label {
          width: 100px;
          text-align: right;
          flex-shrink: 0;
        }
        .unit {
          line-height: 30px;
          background-color: var(--color-fill-2);
          padding: 0 12px;
          margin-left: 10px;
        }
      }
      .img-size-list {
        flex: 1;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        li {
          border: 1px solid #dadde2;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          &.active {
            border-color: rgb(var(--primary-6));
            color: rgb(var(--primary-6));
          }
        }
      }
      .handle-btn-w {
        display: flex;
        justify-content: flex-end;
        margin-top: 40px;
      }
    }
    .price-type {
      font-size: 12px;
      transform: scale(0.82);
      position: relative;
      left: -4px;
    }
    .priview-w {
      background-color: #fff;
      flex: 1;
    }
    .fba-list-w {
      flex: 1;
      height: calc(100vh - @menuHeight);
      overflow-y: auto;
      margin-left: 5px;
      .item {
        min-height: 600px;
        width: 100%;
        background-color: white;
        padding: 10px;
        box-sizing: border-box;
        .top {
          height: 40px;
        }
        .bottom {
          display: flex;
          margin-top: 10px;
          .bottom-item-img {
            min-width: 200px;
            max-width: 580px;
            flex-wrap: wrap;
            img {
              width: 100px;
              height: 100px;
              margin-right: 10px;
            }
          }
          .bottom-item-info {
            flex: 1;
            margin-left: 10px;
          }
        }
      }
    }
  }
</style>
